//TESH.scrollpos=11
//TESH.alwaysfold=0
library DamageSystem initializer Init requires PropertySystem
    // 显示伤害 
    private function ShowDamage takes unit target, real damage,integer damageType returns nothing
            local texttag damageTip = CreateTextTag()
            local string text = I2S(R2I(damage))
            local integer r = 255
            local integer g = 155
            local integer b = 100
            if damageType == 1 then
                set text = "暴击" + text
                set g = 100
                set b = 50
            endif
            if damage <=0 then
                set text = "MISS"
            endif
            call SetTextTagText(damageTip, text, 0.03)
            call SetTextTagColor(damageTip, r, g, b, 255)
            call SetTextTagPos(damageTip, GetUnitX(target), GetUnitY(target), 50.00)
            call SetTextTagVisibility(damageTip, true)
            call SetTextTagVelocityBJ(damageTip,GetRandomReal(80, 120), GetRandomReal(45, 135))
            call YDWETimerDestroyTextTag(GetRandomReal(2, 3),damageTip)
    endfunction
    
    // 伤害公式
    private function DamageEquation takes integer lvAtk,integer lvDef, real atk, real def returns real
        local real from
        if def<0 then
            set def = RAbsBJ(def)
            set from =1 + def/(def+70/lvDef+lvAtk*1.5)
        elseif def>0 then
            set from =1 - def/(def+70/lvDef+lvAtk*1.5)
        else
            set from = 1
        endif
        return atk * from
    endfunction
    
    // 计算伤害值
    private function CalculateDamage takes real atk, unit source,unit target returns real
        local real def = GetUnitState(target, ConvertUnitState(0x20)) 
        local integer lvAtk = GetUnitLevel(source)
        local integer lvDef = GetUnitLevel(target)
        return DamageEquation(lvAtk,lvDef,atk,def)
    endfunction
    
    // 接受伤害事件动作
    private function DamageAction takes nothing returns nothing
        local unit source = GetEventDamageSource()
        local unit target = GetTriggerUnit()
        local real atk = GetEventDamage()
        local integer atkType = 0
        if YDWEIsEventAttackDamage()== false then
            set atk = GetRandomAttackValue(source) * atk * 0.01
        endif
        set atk = CalculateDamage(atk,source,target) * (1 + GetHeroMainProperty(source) * 0.01)
        if GetRandomReal(0, 1) < GetCritOdds(source) then
            set atkType = 1
            set atk = atk * GetCritDamage(source)  
        endif
        call YDWESetEventDamage(atk)
        call ShowDamage(target,atk,atkType)
    endfunction

    private function Init takes nothing returns nothing
        local trigger damage_trigger = CreateTrigger()
        call BJDebugMsg("初始化伤害系统")
        call YDWESyStemAnyUnitDamagedRegistTrigger(damage_trigger)
        call TriggerAddAction(damage_trigger, function DamageAction)
    endfunction

endlibrary

